<script setup>

import {onBeforeMount, ref} from "vue";
import taskRequest from "@/api/task.js"
import projectRequest from "@/api/project.js";
import {useRoute,useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, EditPen, Message, Plus} from "@element-plus/icons-vue";
import TaskAdd from "@/views/task/task-add.vue";

let route = useRoute();
let project = ref({})
let tasks = ref([])
let taskQuery = ref({});
// 全局路由对象
let router = useRouter();
let expandRowKeys = ref([]);
let addWinIsShow = ref(false);
let parentTask = ref(null);
// 当前要编辑的任务的编号，默认是-1
let editTaskId = ref(-1);
let currUserId = ref(-1);
const dialogTaskDetailVisible = ref(false);
const taskDetail = ref(null);
const taskTemp = ref(null)
const dialogTaskEditVisible = ref(false);
const editTask = ref(null);
const dialogCannotDelete = ref(false);
const dialogDeleteVisible = ref(false);
const selectedTasks = ref([]);
const nonDelHandleTaskIds = ref([]);
const dialogUserVisible = ref(false);
const dialogContent = ref([]);
const confirmBatchDelete = ref(false);

//多选编辑
function toToolEditTask(){
  const nonDelHandleTasks = selectedTasks.value;
  // 提取 taskId
  nonDelHandleTaskIds.value = nonDelHandleTasks.map(task => task.taskId);
  // 根据选中的任务数量处理
  if (nonDelHandleTaskIds.value.length > 1) {
    // 任务数量大于 1，显示弹窗提示
    ElMessageBox.alert(
        '同时只能选择一个任务进行编辑',
        '选择任务数量超出限制',
        {
          confirmButtonText: '关闭',
          type: 'warning'
        }
    );
  } else if (nonDelHandleTasks.length === 1) {
    // 任务数量等于 1，输出 taskId 到控制台
    const singleTask = nonDelHandleTasks[0];
    console.log('Selected task:', singleTask);
    if (singleTask && singleTask.taskId) {
      toEditTask(singleTask);
    }
  }
}

//多选请求删除
function deleteTasks (taskId){
  taskRequest.delete(taskId,res =>{

  })
};
//复选框批量选择
const handleSelectionChange = (selectedRows) =>{
  selectedTasks.value = selectedRows;//更新选中的项目

}
//多选请求删除
function toDelTask(){
  const nonDelHandleTasks = selectedTasks.value;
  console.log(nonDelHandleTasks); // 打印所有选中的任务
  console.log(currUserId); // 打印当前用户ID
  // 提取 taskId
  nonDelHandleTaskIds.value = nonDelHandleTasks.map(task => task.taskId);
  // 提取 taskParent
  const taskParents = nonDelHandleTasks.map(task => task.taskParent);
  console.log(taskParents); // 输出所有 taskParent 值
  // 查找 taskParent 为 1 的任务
  const tasksWithParentOne = nonDelHandleTasks.filter(task => task.taskParent === 1);
  console.log(tasksWithParentOne); // 输出 taskParent 为 1 的任务

  // 判断是否存在 taskParent 为 1 的任务
  if (tasksWithParentOne.length > 0) {
    // 设置弹窗内容
    dialogContent.value = tasksWithParentOne;
    dialogUserVisible.value = true; // 显示弹窗
  }else {
    // 显示确认删除弹窗
    ElMessageBox.confirm(
        '当前任务没有父任务，你确定要删除吗?',
        '确认删除？',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(() => {
      // 用户确认删除
      nonDelHandleTaskIds.value.forEach(taskId => {
        console.log(taskId)
        deleteTasks(taskId, res => {
          ElMessage.success(`Successfully deleted task with ID ${taskId}`);
        });
      });
    }).catch(() => {
      // 用户取消删除
      ElMessage.info('删除取消');
    });
  }
}

function confirmDeleteTask(){
  console.log(taskTemp.value.taskId);
  taskRequest.delete(taskTemp.value.taskId,res=>{
    if (res.code == 200){
      console.log("ok")
    }else {
      console.log("error")
    }
    closeDialog();
    loadTasks();
  })
}

//点击删除后进行判断，如果是顶层父节点，那么就弹出不能删除的
function deleteTask(task){
  taskTemp.value = {...task}
  console.log(taskTemp.value.taskId);
  if (task.taskParent == 1){
    dialogCannotDelete.value = true;
  }else {

    dialogDeleteVisible.value = true;
  }
}
function updateTask(editTask){
  console.log(editTask.taskId)
  taskRequest.update(editTask,res=>{
    if (res.code == 200){
      console.log("ok")
    }else {
      console.log("error")
    }
  })
}
/**
 * 新增任务完成的监听事件
 */
function addTaskComplete(task){
  // if (task.taskParentId == 0){
  loadTasks(0);
  // }else{
  //
  // }
}
/**
 * 取消新增的事件
 */
function cancelTaskAdd(){
  addWinIsShow.value = false;
  parentTask = ref(null);
}
/**
 * 工具栏新增按钮事件
 */
function toAddTask(){
  addWinIsShow.value = true;
}

function expandChange(row,expanded){
  console.log(expandRowKeys)
}
//加载子任务
function loadChildrenTask(task,node,resole){
  taskRequest.loadTaskByProjectId(project.value.projectId,task.taskId,res =>{
    resole(res.data);
    console.log(tasks)
  })
}

//点击loadTasks按钮后触发事件
//加载父任务
function loadTasks (parentId){
  console.log(parentId + "abc")
  taskRequest.loadTaskByProjectId(project.value.projectId,parentId,res =>{
    tasks.value = res.data;
  })
}

//加载当前项目对象
function loadProject(projectId){
  projectRequest.getProjectById(projectId,res =>{
    project.value = res.data;
    loadTasks(0);
  })
}
/**
 * 任务详情
 * @param task
 */
function showDetail(task) {
  // 确保将任务详情赋值给响应式的 taskDetail
  taskDetail.value = { ...task }; // 使用展开运算符将 Proxy 对象转化为普通对象
  dialogTaskDetailVisible.value = true;
}
function closeDialog() {
  dialogTaskDetailVisible.value = false;
  dialogTaskEditVisible.value = false;
  dialogCannotDelete.value = false;
  dialogDeleteVisible.value = false;
  dialogUserVisible.value = false;
}
/**
 * 行级新增任务事件
 * @param task
 */
function toAddSubTask(task){
  console.log(task)
  parentTask.value = task;
  addWinIsShow.value = true;
}
/**
 * 行级编辑按钮事件
 * @param task
 */
function toEditTask(task){
  taskRequest.getById(task.taskId,res=>{
    editTask.value = res.data
  })
  console.log(editTask.value.taskId)
  dialogTaskEditVisible.value = true;
}
onBeforeMount(()=>{
  // 获取路由中的参数
  let projectId = route.params.projectId
  if(projectId){
    // 加载项目对象
    loadProject(projectId);
  }else{
    ElMessage({
      type:"info",
      message:"程序出现问题，程序员被祭天!"
    })
    router.push("/home");
  }
  // 获取用户编号
  currUserId = localStorage.getItem("userId");
  console.log(currUserId);

})
</script>

<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>任务管理</el-breadcrumb-item>
        <el-breadcrumb-item>任务列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏-->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-form :model="taskQuery" inline>
        <el-form-item label="任务标题">
          <el-input v-model="taskQuery.taskTitle"/>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select style="width: 100px" v-model="taskQuery.taskStatus">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="正常"/>
            <el-option :value="2" label="暂停"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="loadTasks" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!-- 工具栏 -->
  <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
    <el-col :span="24">
      <el-button-group >
        <el-button :disabled="currUserId!=project.userId"  @click="toAddTask" type="primary">新增</el-button>
        <el-button :disabled="currUserId!=project.userId"  @click="toToolEditTask" type="primary">编辑</el-button>
        <el-button :disabled="currUserId!=project.userId"  @click="toDelTask" type="primary">删除</el-button>
      </el-button-group>
    </el-col>
  </el-row>
  <!-- 数据列表 -->
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-table :data="tasks" border stripe
                row-key="taskId"
                lazy
                :load="loadChildrenTask"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                @expand-change="expandChange"
                :expand-row-keys="expandRowKeys"
                ref="taskTable"
                @selection-change="handleSelectionChange"
      >

        <el-table-column type="selection" width="55"/>
        <el-table-column prop="taskId" label="#">
          <template #default="scope">

            <el-link @click="showDetail(scope.row)" type="success">
              {{ scope.row.taskId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="taskTitle" label="任务标题"/>
        <el-table-column prop="user.username" label="负责人"/>
        <el-table-column label="任务工期" prop="taskDuration"/>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>
        <el-table-column prop="taskStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.taskStatus == 1">正常</el-tag>
            <el-tag type="primary" v-else-if="scope.row.taskStatus == 2">暂停</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <template v-if="scope.row.userId == currUserId || currUserId == project.userId">
              <el-link @click="toAddSubTask(scope.row)"  style="margin: 0px 5px" type="primary"><el-icon><Plus /></el-icon>新增</el-link>
              <el-link @click="toEditTask(scope.row)"  style="margin: 0px 5px" type="primary"><el-icon><EditPen /></el-icon>编辑</el-link>
              <el-link @click="deleteTask(scope.row)"  style="margin: 0px 5px" type="primary"><el-icon><Delete /></el-icon>删除</el-link>
            </template>
              <el-link  style="margin: 0px 5px" type="primary"><el-icon><Message /></el-icon>评论</el-link>

          </template>

        </el-table-column>
      </el-table>

<!--      多选删除的弹出框-->
      <el-dialog v-model="confirmBatchDelete" title="确认删除以下内容吗？">

      </el-dialog>
<!--      删除节点是父节点的弹窗-->
      <el-dialog v-model="dialogUserVisible" title="删除对象警告">
        <el-table :data="dialogContent">
          <el-table-column prop="taskId" label="以下任务存在子任务" width="180">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog">关闭</el-button>
            </span>
      </el-dialog>
<!--      修改任务的弹窗-->
      <el-dialog v-model="dialogTaskEditVisible" title="任务编辑">
        <el-form :model="editTask" ref="formRef" label-width="120px">
          <el-form-item label="项目名称">
            <el-input v-model="editTask.taskTitle"/>
          </el-form-item>
          <el-form-item label="项目描述">
            <el-input type="textarea" v-model="editTask.taskDesc"/>
          </el-form-item>
          <el-form-item label="开始时间" >
            <el-date-picker v-model="editTask.startTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            :style="{width: '100%'}" placeholder="请选择开始时间" clearable/>
          </el-form-item>
          <el-form-item label="结束时间" >
            <el-date-picker v-model="editTask.endTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            :style="{width: '100%'}" placeholder="请选择结束时间" clearable/>
          </el-form-item>
          <el-form-item label="工期">
            <el-input-number v-model="editTask.taskDuration" placeholder="工期"/>
          </el-form-item>
          <el-form-item label="进度">
            <el-slider :max='100' :step='1' v-model="editTask.taskProgress"></el-slider>
          </el-form-item>
          <el-form-item label="状态" prop="field104">
            <el-select v-model="editTask.taskStatus" placeholder="请选择状态" clearable :style="{width: '100%'}">
              <el-option :value="1" label="正常"/>
              <el-option :value="2" label="暂停"/>
            </el-select>
          </el-form-item>
        </el-form>


        <span slot="footer" class="dialog-footer">
          <el-button @click="updateTask(editTask)" type="primary">提交</el-button>
              <el-button @click="closeDialog">关闭</el-button>
            </span>
      </el-dialog>
<!--      任务详情的弹窗-->
      <el-dialog v-model="dialogTaskDetailVisible" title="任务详情">
        <div v-if="taskDetail">
          <p>任务名称:{{taskDetail.taskTitle}}</p>
          <p>任务详情:{{taskDetail.taskDesc}}</p>
          <p>任务进展:{{taskDetail.taskProgress}}</p>
          <p>任务周期:{{taskDetail.taskDuration}}</p>
        </div>
        <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog">关闭</el-button>
            </span>
      </el-dialog>

<!--      确认删除的弹窗-->
      <el-dialog v-model="dialogDeleteVisible" title="确定要删除吗?">
        <div v-if="taskTemp">
          <p>任务名称: {{ taskTemp.taskTitle }}</p>
        </div>

        <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="confirmDeleteTask">
          确认
        </el-button>
        <el-button type="success" @click="closeDialog">
          取消
        </el-button>
        </span>

      </el-dialog>
<!--      删除失败的弹窗-->
      <el-dialog v-model="dialogCannotDelete" title="提示">
        <div>
          <p>此任务下有子任务,你不能删除它</p>
        </div>
        <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog">关闭</el-button>
            </span>
      </el-dialog>
    </el-col>
  </el-row>
  <!-- 新增弹窗组件 -->
  <taskAdd @cancelTaskAdd="cancelTaskAdd" @add-complete="addTaskComplete" :project="project" :is-show="addWinIsShow" :parent-task="parentTask"/>


</template>

<style scoped>

</style>